package com.app.trafficclient.geRenZhongXin;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.android.volley.toolbox.Volley;
import com.app.trafficclient.MainActivity;
import com.app.trafficclient.R;
import com.app.trafficclient.util.MyLoadDialog;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link Fragment1.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link Fragment1#newInstance} factory method to
 * create an instance of this fragment.
 */
public class Fragment1 extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public Fragment1() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment Fragment1.
     */
    // TODO: Rename and change types and number of parameters
    public static Fragment1 newInstance(String param1, String param2) {
        Fragment1 fragment = new Fragment1();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        sendPost();
    }

    @Override
    public void onStop() {
        super.onStop();
        linearAdd.removeAllViews();
    }

    //   姓名   性别   电话  身份证  注册时间
    TextView name,sex,phone,id,regTime;
    ImageView touXiang;
    //动态添加车标那行
    LinearLayout linearAdd;
    //动画
    MyLoadDialog myLoadDialog;
    //注册时间，格式化
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd");
    int sumCars; // 个人总车数
    //其中的一个车标的布局
    LinearLayout linearLayout;
    //两个 布局宽高等
    LinearLayout.LayoutParams layoutParams,layoutParams1;
//    存个人所有车牌
    String[] chePai;
//    存个人所有车型
    String[] cheXing;
    //请求队列
    RequestQueue requestQueue;
    Handler handler;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_fragment1, container, false);
        name = view.findViewById(R.id.personal_frag1_name);
        sex = view.findViewById(R.id.personal_frag1_sex);
        phone = view.findViewById(R.id.personal_frag1_phone);
        id = view.findViewById(R.id.personal_frag1_id);
        regTime = view.findViewById(R.id.personal_frag1_regTime);
        touXiang = view.findViewById(R.id.personal_frag1_touxiang);
        linearAdd = view.findViewById(R.id.bill_liner_add);
        return view;
    }

   //个人信息
    private void sendPost(){
        showDialog();
        String url ="http://www.wpwh.info/user/info";
        requestQueue = Volley.newRequestQueue(getContext());
        Map<String, String> map = new HashMap<>();
        map.put("username", "user1");   //这里改为当前登录的用户
//        Log.d("tag1", merchant.toString());
        JSONObject jsonObject = new JSONObject(map);//以json串方式请求
        JsonRequest<JSONObject> jsonRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        //Log.d("frag1", "response -> " + response.toString());
                        String string = response.toString();
                        Gson gson = new Gson();
                        BeanFrag1Person myClassFragment1 = gson.fromJson(string,BeanFrag1Person.class);
                        if (myClassFragment1.getSex().equals("男")){
                            touXiang.setImageResource(R.drawable.touxiang_2);
                        }else {
                            touXiang.setImageResource(R.drawable.touxiang_1);
                        }
                        name.setText("姓名："+myClassFragment1.getUsername());
                        sex.setText("性别："+myClassFragment1.getSex());
                        phone.setText("手机号码："+myClassFragment1.getPhone());
                        id.setText("身份证号："+myClassFragment1.getId());
                        Date date =new Date(myClassFragment1.getRegistered()); //把json串返回的 长整型 存到data
                        regTime.setText("注册时间："+String.valueOf(formatter.format(date))); // 把设定好的格式   格式化日期
                        sendPostCars();  // 在查询 车辆信息
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(2000);
                            dismissdialog();
                            handler.sendEmptyMessage(1);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
             handler = new Handler(){
                 @Override
                 public void handleMessage(Message msg) {
                     getActivity().onBackPressed();
                     MainActivity.wangluoIsNull();
                 }
             };
            }
        });
        requestQueue.add(jsonRequest);
    }//sendPost

    //个人所有车辆
    private void sendPostCars(){
        String url ="http://www.wpwh.info/user/cars";
        requestQueue = Volley.newRequestQueue(getContext());

        Map<String, String> map = new HashMap<String, String>();
        map.put("username", "user1");   //这里改为当前登录的用户
        JSONObject jsonObject = new JSONObject(map);

        JsonRequest<JSONObject> jsonRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
//                        Log.d("frag1--return--Cars",  response.toString());
                        String string = response.toString();
                        Gson gson = new Gson();
                        BeanFrag1Cars myClassFragment1_cars = gson.fromJson(string,BeanFrag1Cars.class);
                        sumCars =myClassFragment1_cars.getCars().size();
                        chePai = new String[sumCars];
                        cheXing = new String[sumCars];
                        for (int i = 0;i<sumCars;i++){
                            chePai[i] = myClassFragment1_cars.getCars().get(i).getLicense();
                            cheXing[i] = myClassFragment1_cars.getCars().get(i).getBrand();
//                            Log.d("TAGGG",String.valueOf(chePai[i]));
//                            Log.d("TAGGG",String.valueOf(cheXing[i]));
                        }

                         layoutParams =new LinearLayout.LayoutParams
                                (LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
                        layoutParams.setMargins(0,15,0,0);
                        layoutParams1 =new LinearLayout.LayoutParams
                                (0,LinearLayout.LayoutParams.MATCH_PARENT,1);
                       if (sumCars >0){
                               setRow();
                        } // if
                        dismissdialog();
                    }//onResponse

                    private void setRow() {
                        linearLayout =new LinearLayout(getContext());
                        linearLayout.setLayoutParams(layoutParams);
                        for (int i=0;i<sumCars;i++) {
                           // Log.d("tagggggg",String.valueOf(hangShu * i));
                            LinearLayout linearLayout1 = new LinearLayout(getContext());
                            linearLayout1.setGravity(Gravity.CENTER);
                            linearLayout1.setOrientation(LinearLayout.VERTICAL);
                            linearLayout1.setLayoutParams(layoutParams1);  // 0 ,M,1
                            ImageView imageView = new ImageView(getContext());
                            if (cheXing[i].equals("aodi")){
                                imageView.setImageDrawable(getResources().getDrawable(R.drawable.audi));
                            }else if (cheXing[i].equals("bugatti veyron")){
                                imageView.setImageDrawable(getResources().getDrawable(R.drawable.audi));//没有这个车标
                            }else if (cheXing[i].equals("bentian")){
                                imageView.setImageDrawable(getResources().getDrawable(R.drawable.bentian));
                            }else if (cheXing[i].equals("dazhong")){
                                imageView.setImageDrawable(getResources().getDrawable(R.drawable.dazhong));
                            }
                            else if (cheXing[i].equals("baoma")){
                                imageView.setImageDrawable(getResources().getDrawable(R.drawable.baoma));
                            }
                            else if (cheXing[i].equals("fute")){
                                imageView.setImageDrawable(getResources().getDrawable(R.drawable.fute));
                            }else if (cheXing[i].equals("zhonghua")){
                                imageView.setImageDrawable(getResources().getDrawable(R.drawable.zhonghua));
                            }else if (cheXing[i].equals("bentley")){
                                imageView.setImageDrawable(getResources().getDrawable(R.drawable.benchi));
                            }else if (cheXing[i].equals("xiandai")){
                                imageView.setImageDrawable(getResources().getDrawable(R.drawable.xiandai));
                            }else if (cheXing[i].equals("biyadi")){
                                imageView.setImageDrawable(getResources().getDrawable(R.drawable.biyadi));
                            }else {
                                imageView.setImageDrawable(getResources().getDrawable(R.drawable.audi));  // 测试：如果服务器返回的车标没有，就用这个代替
                            }
//                            imageView.setImageDrawable(getResources().getDrawable(aoDi));
                            TextView  tvChePai = new TextView(getContext());
                            tvChePai.setText(chePai[i]);
                            tvChePai.setTextColor(getResources().getColor(R.color.listfontfocused));
                            linearLayout1.addView(imageView);
                            linearLayout1.addView(tvChePai,LinearLayout.LayoutParams.WRAP_CONTENT,
                                                           LinearLayout.LayoutParams.WRAP_CONTENT);
                            linearLayout.addView(linearLayout1);
                        } // for
                        linearAdd.addView(linearLayout);
                    } //setRow

                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                dismissdialog();
                getActivity().onBackPressed();
                MainActivity.wangluoIsNull();
            }
        });
        requestQueue.add(jsonRequest);
    }//sendPostCars
    private void dismissdialog() {
        myLoadDialog.dismiss();
    }

    private void showDialog() {
        myLoadDialog = new MyLoadDialog(getContext());
        myLoadDialog.setCanceledOnTouchOutside(false);
        myLoadDialog.show();
    }


    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

}
